﻿using System;
using System.IO;
using System.Data;
using LumenWorks.Framework.IO.Csv;

namespace Utilities
{
    public class CSVUtil
    {
        public static void saveDataTableToCSVFile(DataTable datatableSource, string strFileCSVDestination)
        {
            #region Export Grid to CSV
            // Create the CSV file to which grid data will be exported.
            StreamWriter sw = new StreamWriter(strFileCSVDestination, false);

            // First we will write the headers.
            int iColCount = datatableSource.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(datatableSource.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);

            // Now write all the rows.
            foreach (DataRow dr in datatableSource.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
            #endregion
        }
    }
}
